﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using TestBat.Frontend.Controllers.Factories;
using TestBat.ServiceLocator;

namespace TestBat.Frontend
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Index", action = "Index", id = "" }  // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);

            // setup GuyWire
            var guyWireClassKey = ConfigurationManager.AppSettings.Keys.Cast<string>().FirstOrDefault(k => "guywire".Equals(k.ToLowerInvariant()));
            var guyWireClass = ConfigurationManager.AppSettings[guyWireClassKey];
            var type = Type.GetType(guyWireClass);
            guyWire = (IGuyWire.IGuyWire)Activator.CreateInstance(type);

            // start GuyWire
            guyWire.Wire();

            // enable logging
            log4net.Config.XmlConfigurator.Configure();

            ControllerBuilder.Current.SetControllerFactory(DefaultServiceLocator.Get<ControllerFactory>());
        }

        protected void Application_End()
        {
            guyWire.Dewire();
        }

        private IGuyWire.IGuyWire guyWire;
    }
}